package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.business.domain.HistoricActivity;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.service.IProcessDifinitionService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.common.core.text.Convert;

/**
 * 审核列表Service业务层处理
 * 
 * @author shuangwaiwai
 * @date 2021-10-16
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService 
{
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IProcessDifinitionService processDifinitionService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询审核列表
     * 
     * @param id 审核列表ID
     * @return 审核列表
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询审核列表列表
     * 
     * @param carPackageAudit 审核列表
     * @return 审核列表
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit)
    {
        //设置查询条件创建人为当前用户
        carPackageAudit.setCreateBy(String.valueOf(ShiroUtils.getUserId()));


        List<CarPackageAudit> carPackageAuditList = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for (CarPackageAudit packageAudit : carPackageAuditList) {
            List<Task> task = processDifinitionService.getTaskByInstanceId(packageAudit.getInstanceId());
            if(!CollectionUtils.isEmpty(task)) {
                for (Task task1 : task) {
                    packageAudit.setTaskId(task1.getId());
                    packageAudit.setTaskName(task1.getName());
                }
            } else {
                packageAudit.setTaskName("已结束");
            }
//            ServiceItem serviceItem = JSON.parseObject(packageAudit.getServiceItemInfo(), ServiceItem.class);
//            packageAudit.setServiceItem(serviceItem);
        }
        return carPackageAuditList;
    }

    /**
     * 新增审核列表
     * 
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改审核列表
     * 
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 删除审核列表对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids)
    {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核列表信息
     * 
     * @param id 审核列表ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

    @Override
    public void cancelApply(Long auditId, String instanceId) {
        CarPackageAudit carPackageAudit = selectCarPackageAuditById(auditId);
        if(carPackageAudit==null) {
            throw new BusinessException("非法操作，审核记录不存在");
        }
        String createBy = carPackageAudit.getCreateBy();
        if(!ShiroUtils.getUserId().toString().equals(createBy)) {
            throw new BusinessException("审核记录不存在");
        }
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("只有进行中的审核可以撤销");
        }
        //一.修改审核记录相关信息（状态，当前审核人）
        carPackageAudit.setAuditors("");
        carPackageAudit.setStatus(CarPackageAudit.STATUS_CANCEL);
        this.updateCarPackageAudit(carPackageAudit);
        //二.修改服务状态为初始化
        ServiceItem serviceItem = carPackageAudit.getServiceItem();
        serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        //将审核中的状态修改为初始状态
        serviceItemService.updateStatus(serviceItem.getId(),ServiceItem.AUDITSTATUS_AUDITING,ServiceItem.AUDITSTATUS_INIT);
        //三.访问activiti的API 将流程实例删除
        SysUser sysUser = ShiroUtils.getSysUser();
        processDifinitionService.deleteProcessInstance(instanceId,sysUser.getUserName()+"撤销了申请");
    }

    @Override
    public List<HistoricActivity> selectHistoricActivity(String instanceId) {
        //1.通过activity7查询历史活动列表（指定实例id）
        List<HistoricActivityInstance> historicActivityInstances = processDifinitionService.getHistoricActivityListByInstanceId(instanceId);

        List<HistoricActivity> resultList = new ArrayList<>(historicActivityInstances.size());

        HistoricActivity activity;
        //2.遍历历史活动列表，将对象转换为HistoricActivity
        for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
            activity=new HistoricActivity();
            BeanUtils.copyProperties(historicActivityInstance,activity);
            //3.查询分配人的姓名设置到活动对象中
            String assignee = activity.getAssignee();
            if(StringUtils.isNotEmpty(assignee)) {
                SysUser sysUser = sysUserService.selectUserById(Long.parseLong(assignee));
                activity.setAssigneeName(sysUser.getUserName());
            }
            //4.查询该任务对应的批注信息设置到活动对象中
            String comment = processDifinitionService.getTaskCommentByTaskId(activity.getTaskId());

            activity.setComment(comment);

            //将任务对象加入到结果集中
            resultList.add(activity);

        }
        return resultList;
    }
}
